#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define CREATER "creater"
#define USER "user"
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

const int gdefaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66;
const int gmode = 0666;

class Shm
{
private:
    void CreateHelper(int flg)
    {

        printf("key: 0x%x\n", _key);
        // 共享内存的生命周期随内核
        //
        _shmid = shmget(_key, _size, flg);
        if (_shmid < 0)
        {
            ERR_EXIT("shmid\n");
        }
        printf("shmid: %d\n", _shmid);
    }

    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | 0666);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat\n");
        }
        printf("attach success!\n");
    }

    void Get()
    {
        // key_t k = ftok(pathname.c_str(), projid);
        // if (k < 0)
        // {
        //     ERR_EXIT("ftok\n");
        // }
        // printf("key: 0x%x\n", k);
        // // 共享内存的生命周期随内核
        // //
        // _shmid = shmget(k, _size, IPC_CREAT);
        // if (_shmid < 0)
        // {
        //     ERR_EXIT("shmid\n");
        // }
        // printf("shmid: %d\n", _shmid);
        CreateHelper(IPC_CREAT);
    }

    void Destroy()
    {
        if (_shmid == gdefaultid)
            return;
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if (n > 0)
        {
            printf("shmctl delete shm: %d success!\n", _shmid);
        }
        else
        {
            ERR_EXIT("shmctl\n");
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &usertype)
        : _shmid(gdefaultid),
          _size(gsize),
          _start_mem(nullptr),
          _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok\n");
        }
        if (_usertype == CREATER)
            Create();
        else if (_usertype == USER)
            Get();
        else
        {
        }
        Attach();
    }

    void *VirtualAddr()
    {
        printf("VirtualAddr: %p\n", _start_mem);
        return _start_mem;
    }

    int Size()
    {
        return _size;
    }

    ~Shm()
    {
        if(_usertype == CREATER) Destroy();
    }

private:
    int _shmid;
    key_t _key;
    int _size;
    void *_start_mem;
    std::string _usertype;
};